package com.ppgames.gm.gmsystem.auth;

import com.ppgames.gm.gmsystem.DemoRunnable;
import com.ppgames.gm.gmsystem.GmCore;
import com.ppgames.gm.gmsystem.util.JsonHelper;
import com.ppgames.gm.gmsystem.util.Resp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * TODO:写点说明把
 *
 * @author Joeg
 * @email 840459673@qq.com
 * @date 2018/4/19
 */
@Controller
@RequestMapping("/auth")
public class AuthController {

    private static ExecutorService executorService = Executors.newCachedThreadPool();

    public static void newThread(Runnable fun) {
        executorService.execute(fun);
    }
    @Autowired
    DemoRunnable demoRunnable;


    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    AuthService authService;

    @PostMapping("/login")
    @ResponseBody
    public Resp login(@RequestBody LoginReq req) {
        String account = req.getAccount();
        String password = req.getPassword();
        if (account == null || account.isEmpty() || password == null || password.isEmpty()) {
            return Resp.customFail("1", "账号或密码不能为空");
        }

        Resp resp = authService.login(req);
        if (!resp.ok()) {
            return resp;
        }

        String token = GmCore.Util.createUUID();
        OptInfo optInfo = new OptInfo();
        optInfo.setToken(token);
        optInfo.setAccountCode(req.getAccount());
        optInfo.setLastLoginTime(new Date());
        optInfo.setExt(JsonHelper.toJsonString(resp.getBody()));
        CacheManager.addToken(optInfo);

        logger.info("auth login success: {}", JsonHelper.toJson(optInfo));
        return Resp.success(optInfo);
    }

    @GetMapping("/test")
    public String jspTest(Model model) {
        model.addAttribute("aa", "Hello World!");
        return "test";
    }
}
